package yf.mall.controller.api.app;

import com.yf.annotation.IgnoreAuth;
import com.yf.annotation.LoginUserId;
import com.yf.response.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import yf.mall.entity.AppConfigEntity;
import yf.mall.enums.app.AppBehaviorTypeEnum;
import yf.mall.service.app.AppBehaviorService;
import yf.mall.service.app.AppConfigService;
import yf.mall.utils.app.AppUtil;
import yf.mall.component.app.AppMaterialComponent;
import yf.mall.component.app.AppProductComponent;
import yf.mall.component.app.QiniuFileComponent;
import yf.mall.entity.AppCategoryEntity;
import yf.mall.entity.AppFavoriteEntity;
import yf.mall.enums.app.AppCategoryTypeEnum;
import yf.mall.enums.app.AppCollectTypeEnum;
import yf.mall.enums.app.AppDateTypeEnum;
import yf.mall.service.app.AppCategoryService;
import yf.mall.service.app.AppFavoriteService;
import yf.mall.vo.app.common.ClassificationVo;
import yf.mall.vo.app.common.DataResult;
import yf.mall.vo.app.common.ListQuery;
import yf.mall.vo.app.request.AppMaterialListRequest;
import yf.mall.vo.app.request.CommonRequest;
import yf.mall.vo.app.common.ListResult;
import yf.mall.vo.app.request.DailyStatisticsRequest;
import yf.mall.vo.app.product.KolProductVo;
import yf.mall.vo.app.request.ProductListRequest;
import yf.mall.vo.app.product.TotalStatisticsVo;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@RestController
@RequestMapping("/api/app/mini/selection")
public class ApiAppProductController extends ApiAppBaseController {

    @Resource
    private AppProductComponent appProductComponent;

    @Resource
    private AppCategoryService appCategoryService;

    @Resource
    private AppFavoriteService appFavoriteService;

    @Resource
    private AppMaterialComponent appMaterialComponent;

    @Resource
    private AppConfigService appConfigService;

    @Resource
    private AppBehaviorService appBehaviorService;


    @RequestMapping(value = "/detail",
            produces = {"application/json"},
            method = RequestMethod.POST)
    @IgnoreAuth
    public R appSelectionDetail(HttpServletRequest request, @RequestBody CommonRequest commonRequest) {
        Long pid = commonRequest.getPid();
        Long userId = getLoginUser(request);
        KolProductVo kolProductVo = appProductComponent.getKolProductDetail(pid, userId);
        return dataResult(kolProductVo);
    }


    @RequestMapping(value = "/list",
            method = RequestMethod.POST)
    @IgnoreAuth
    public R appSelectionList(@RequestBody(required = true) ProductListRequest request) {
        ListResult<KolProductVo> kolProductList = appProductComponent.getKolProductList(request, null);
        return dataResult(kolProductList);
    }

    @RequestMapping(value = "/list/V2",
            method = RequestMethod.POST)
    @IgnoreAuth
    public R appSelectionListV2(@RequestBody(required = true) ProductListRequest request) {
        ListResult<KolProductVo> kolProductList = appProductComponent.getKolProductList(request, null);
        return dataResult(kolProductList);
    }

    @RequestMapping(value = "/classification",
            method = RequestMethod.POST)
    @IgnoreAuth
    public R selectionClassification() {
        AppCategoryEntity rootCategory = appCategoryService.getRootCategory(AppCategoryTypeEnum.PRODUCT_CATEGORY_ROOT.getType());
        if (rootCategory == null) {
            return R.ok(Collections.emptyList());
        }
        List<AppCategoryEntity> appCategoryEntities = appCategoryService.getCategoryByParent(rootCategory.getType(), rootCategory.getRootId());
        return dataResult(appCategoryEntities.stream().map(ClassificationVo::build).collect(Collectors.toList()));
    }

    @RequestMapping(value = "/detail/V2",
            method = RequestMethod.POST)
    @IgnoreAuth
    public R selectionDetailV2(HttpServletRequest request, @RequestBody CommonRequest commonRequest) {
        Long userId = getLoginUser(request);
        Long pid = commonRequest.getPid();
        KolProductVo kolProductVo = appProductComponent.getKolProductDetail(pid, userId);
        return dataResult(kolProductVo);
    }

    @RequestMapping(value = "/video",
            method = RequestMethod.POST)
    public R selectionVideo(@LoginUserId Long userId, @RequestBody CommonRequest request) {
        Long pid = request.getPid();
        AppMaterialListRequest materialRequest = new AppMaterialListRequest();
        materialRequest.setId(pid);
        materialRequest.setType(AppCategoryTypeEnum.HOT_VIDEO_URL.getType());
        appMaterialComponent.getVideoMaterialList(materialRequest);
        return dataResult(new ListResult<>(Collections.emptyList(), false));
    }

    @RequestMapping("/pmt-type")
    public R selectionPmtType() {
        List<AppConfigEntity> productPmtTypeConfig = appConfigService.findConfigByKey(Collections.singletonList("product_pmt_type_config"));
        if (productPmtTypeConfig.isEmpty()) {
            return jsonDataResult("[{\"name\":\"2小时\",\"value\":0,\"items\":[1]},{\"name\":\"24小时\",\"value\":1,\"items\":[1]},{\"name\":\"近7日\",\"value\":2,\"items\":[1,2,3]},{\"name\":\"近30日\",\"value\":3,\"items\":[1,2,3]}]");
        }
        return jsonDataResult(productPmtTypeConfig.stream().map(AppConfigEntity::getValue).findFirst().orElse(""));
    }

    @RequestMapping(value = "/pmt",
            method = RequestMethod.POST)
    public R selectionPmt(@RequestBody DailyStatisticsRequest request) {
        Long pid = request.getId();
        TotalStatisticsVo totalStatisticsVo = new TotalStatisticsVo();

        if (request.getType() == 0) {
            totalStatisticsVo = appProductComponent.getKolProduct24Stat(pid, 2);
        } else if (request.getType() == 1) {
            totalStatisticsVo = appProductComponent.getKolProduct24Stat(pid, 24);
        } else if (request.getType() == 2) {
            totalStatisticsVo = appProductComponent.getKolProductStatistics(pid, AppUtil.getBeginByType(AppDateTypeEnum.DAY_7.getType()), AppUtil.getEndByType(AppDateTypeEnum.DAY_7.getType()));
        } else if (request.getType() == 3) {
            totalStatisticsVo = appProductComponent.getKolProductStatistics(pid, AppUtil.getBeginByType(AppDateTypeEnum.DAY_30.getType()), AppUtil.getEndByType(AppDateTypeEnum.DAY_30.getType()));
        } else if (request.getType() == 4) {
            totalStatisticsVo = appProductComponent.getKolProductStatistics(pid, AppUtil.getBeginByType(AppDateTypeEnum.DAY_3.getType()), AppUtil.getEndByType(AppDateTypeEnum.DAY_3.getType()));
        } else if (request.getType() == 5) {
            totalStatisticsVo = appProductComponent.getKolProductStatistics(pid, AppUtil.getBeginByType(AppDateTypeEnum.DAY_15.getType()), AppUtil.getEndByType(AppDateTypeEnum.DAY_15.getType()));
        }
        return dataResult(totalStatisticsVo);
    }

    @RequestMapping(value = "/market-type",
            method = RequestMethod.POST)
    @IgnoreAuth
    public R selectionMarketType() {
        AppCategoryEntity rootCategory = appCategoryService.getRootCategory(AppCategoryTypeEnum.PRODUCT_MARKET_ROOT.getType());
        if (rootCategory == null) {
            return R.ok(Collections.emptyList());
        }
        List<AppCategoryEntity> appCategoryEntities = appCategoryService.getCategoryByParent(rootCategory.getType(), rootCategory.getRootId());
        return dataResult(appCategoryEntities.stream().map(ClassificationVo::build).collect(Collectors.toList()));
    }

    @RequestMapping(value = "/store-add",
            method = RequestMethod.POST)
    public R appStoreAdd(@LoginUserId Long userId, @RequestBody CommonRequest request) {
        log.info("用户{}操作添加橱窗，添加商品为{}", request.getDisplayId(), request.getPid());
        Long pid = request.getPid();
        DataResult result = appProductComponent.storeAdd(userId, pid, request.getDisplayId());
        if (!result.getSuccess()) {
            return R.error(result.getResult().toString(), null);
        }
        String behavior = "用户" + request.getDisplayId() + "操作添加橱窗,添加商品为" + request.getPid();
        appBehaviorService.record(userId, request.getPid(), AppBehaviorTypeEnum.ADD_STROE.getKey(), behavior, 10);
        return R.ok();
    }

    @RequestMapping(value = "/collect-list",
            method = RequestMethod.POST)
    public R collectList(@LoginUserId Long userId, @RequestBody ListQuery listQuery) {
        if (userId == null) {
            return R.error("获取不到登录用户");
        }
        AppFavoriteEntity query = new AppFavoriteEntity();
        query.setCollectorId(userId);
        query.setType(AppCollectTypeEnum.PRODUCT.getKey());
        query.setStatus(1);
        List<AppFavoriteEntity> appFavoriteEntities = appFavoriteService.find(query);
        if (appFavoriteEntities.isEmpty()) {
            return dataResult(new ListResult<>(Collections.emptyList(), false));
        }
        List<Long> productIds = appFavoriteEntities.stream().map(AppFavoriteEntity::getRefId).collect(Collectors.toList());
        ProductListRequest request = new ProductListRequest();
        request.setPage(listQuery.getPage());
        request.setLimit(listQuery.getLimit());
        request.setProductIds(productIds);
        ListResult<KolProductVo> kolProductList = appProductComponent.getKolProductList(request, userId);
        return dataResult(kolProductList);
    }
}